var $$scope;
var $CertusFormAjax;
var dataInitQuote;
var quoteDatagrid;
var projId;
var dataInitQuoteold;
var totalmoney = 0;
var randomId;
var biId = 0;
function editPrice($scope, $route, CertusFormAjax, CertusJsonAjax, $location, $http, $cookies, $routeParams) {
    $$scope = $scope;
    $CertusFormAjax = CertusFormAjax;

    $(".quoteItemOld").hide();
    $(".totalQuoteOld").hide();

    var oabtOption1 = {
        lang: 'zh-cn',
        ajaxLoad: false,
        // loadURL:'url',
        exportFileName: '报价条目列表',
        datas: [],
        columns: quoteItemPronum1,
        gridContainer: 'priceContainerold',
        toolbarContainer: 'priceToolBarContainerold',
        tools: '',
        pageSize: 10,
        pageSizeLimit: [10, 15, 20]
    };
    //报价条目 datagrid 需求 变更 此表不查询
    dataInitQuoteold = $.fn.dlshouwen.grid.init(oabtOption1);
    dataInitQuoteold.load();
    dataInitQuoteold.refresh(false);

    var oabtOption1 = {
        lang: 'zh-cn',
        ajaxLoad: false,
        // loadURL:'url',
        exportFileName: '报价条目列表',
        datas: [],
        columns: quoteItemPronum,
        gridContainer: 'priceContainer',
        toolbarContainer: 'priceToolBarContainer',
        tools: '',
        pageSize: 10,
        pageSizeLimit: [10, 15, 20]
    };
    //报价条目 datagrid 需求 变更 此表不查询
    dataInitQuote = $.fn.dlshouwen.grid.init(oabtOption1);
    dataInitQuote.load();
    dataInitQuote.refresh(false);

    // dataInitold = CertusJsonAjax.dataInitQuote("quoteItemList", {projId: "111"}, quoteItemPronum1, 'priceContainerold', 'priceToolBarContainerold');

    $$scope.business = {};
    $$scope.businessold = {};

    

    if ($routeParams.projId) {
        projId = $routeParams.projId;
        $scope.item = { projId: projId };
        $scope.business = { projId: projId };
        //初始化 已通过 报价 或者 未通过报价


        //初始化 报价条目 下拉选择框
        $scope.categorySelect = [
            { categoryName: '软件', category: "1" },
            { categoryName: '软件license', category: "2" },
            { categoryName: '硬件', category: "3" },
            { categoryName: '服务', category: "4" },
            { categoryName: '软件定制', category: "5" },
            // { categoryName: '一次性折扣', category: "6" }
        ];

        $scope.hideprice = function () {
            $scope.item.projId = projId;
            caculateTotal(dataInitQuote.exhibitDatas);
            $(".hideprice").hide();
        }

        $scope.quoteItemSubmit = function () {
            if (certusValidateNotnullPolyfill()) {
                // $scope.item.taxPrice = to2fixed(($scope.item.cataPrice*$scope.item.discountedRate/100)*(1+$scope.item.taxRate/100));
                // $scope.item.discountPrice = $scope.item.cataPrice * $scope.item.discountedRate / 100;
                // CertusJsonAjax.ajax("quoteItemSubmit", $scope.item, function (res) {
                //     if (res.data && res.data == "success") {
                //         $scope.item = {projId: projId};
                //         $(".hideprice").hide();
                //         dataInitQuote.refresh(true);
                //     }
                // })

                randomId = $scope.item.randomId;
                dataInitQuote.exhibitDatas = dataInitQuote.exhibitDatas.filter(isDiffQuote);

                // totalmoney += $scope.item.taxPrice
                // $$scope.business.totalBusinessQuatation = totalmoney;
                dataInitQuote.refresh(false);
                $scope.item.randomId = biId++;
                dataInitQuote.exhibitDatas.push($scope.item);

                //
                caculateTotal(dataInitQuote.exhibitDatas);

                // dataInitQuote.refresh(false);
                $(".hideprice").hide();
            }
        }

        var fileInstantiation = {
            classCateCode: 'NBCPYZ',
            fileClassCode: 'TBSWWD'
        }
        var fileInstantiationDisable = {
            classCateCodeDis: true, //文件类目不可修改
            fileClassCodeDis: true //文件类型不可修改
        }
        //调用初始化方法
        initFileUpload($$scope, fileInstantiation, fileInstantiationDisable, $CertusFormAjax);

        $scope.businessQuoteSubmit = function () {
            if (dataInitQuote.exhibitDatas && dataInitQuote.exhibitDatas.length > 0) {
                //调用公共方法 上传文件
                var $CertusJsonAjax = CertusJsonAjax
                fileUpload($$scope,
                    function (res) {
                        $$scope.business.originReason = 'approval';
                        $$scope.business.uploadFilePath = res.data;
                        $$scope.business.templateCode = 'SWBJLC';
                        $$scope.business.quotes = dataInitQuote.exhibitDatas;
                        $$scope.business.projId = projId;
                        $CertusJsonAjax.ajax("startBusinessQuote", $$scope.business, function (res) {
                            //刷新 底部 页面
                            hasQuoteApply();
                        })
                    },
                    function (res) {
                        layer.msg("请勿上传空文件");
                    });
            } else {
                layer.msg("请补充报价条目");
            }
        }



        //方法 被调用时 建立 连接
        $scope.socket = CertusJsonAjax.socketNode("businessTotalPrice","",function(socket){

            socket.on("connection", function (msg, b, c) {
                console.log("connection created");
            })
            socket.on("message", function (data, b, c) {

               if(socket.id == data){
                   //报价数据
                   quoteDatagrid = CertusJsonAjax.dataInit("businessQuoteList", { projId: $routeParams.projId }, piclogColumns, "piclogContainer", "piclogToolBarContainer")
                   hasQuoteApply();
               }else{
                    $scope.business.totalBusinessQuatation = data.total;
                   dataInitQuote.exhibitDatas = data.datas;
                   dataInitQuote.refresh(false);
                   $scope.$apply();
               }
            })
        });
        
        $$scope.classfictionselect = [
            { name: '请选择', value: "xxxx" },
            { name: '内部保密', value: "0" },
            { name: '内部公开', value: "1" },
            { name: '完全公开', value: "2" }
        ];

        $$scope.rangeSelect = [
            { name: '请选择', value: "xxxx" },
            { name: '公司内部', value: "0" },
            { name: '公开信息', value: "1" }
        ]

        $$scope.permissionSelect = [
            { name: '请选择', value: "xxxx" },
            { name: '总经理', value: "0" },
            { name: '总监', value: "1" },
            { name: '本部门', value: "2" }
        ]

        var picker2 = $('#datetime').datetimepicker({
            format: 'YYYY-MM-DD',
            locale: moment.locale('zh-cn')
        }).on('dp.change', function (e) {
            var result = new moment(e.date).format('YYYY-MM-DD');
            if (result && !angular.isUndefined(result)) {
                $$scope.file.validity = result;
                $$scope.$apply();
            }
        })

    }
}

// 商务报价条目管理显示隐藏
function showprice() {
    $$scope.item = {};

    $$scope.$apply();
    // $$scope.retainPrice = 0;
    $(".hideprice").show();
}

function hasQuoteApply() {
    $(".hide-quote-panel").hide();
    $(".newOldDiv").hide();

    $(".hidefile").hide();
    $CertusFormAjax.ajax("hasQuoteApply", { projId: projId }, function (res) {
        if (res.data == "success") {
            $(".hide-quote-panel").show();
            $(".newOldDiv").show();
        } else {
            layer.msg("当前报价流程，正在 " + res.data + " 处处理。");
        }
    })
}

function down(uploadPath) {
    $CertusFormAjax.download("attachmentDownBusiness", "uploadFilePath=" + uploadPath);
}

//originReason veto promise denied approval

// 商务报价-历史记录
var piclogColumns = [{
    id: 'createTime',
    title: '提交日期',
    width: 140,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var date = new Date(record.createTime);
        var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy/MM/dd hh:mm");
        return content;
    }
}, {
    id: 'createUserName',
    title: '提交人',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
}, {
    id: 'totalBusinessQuatation',
    title: '商务报价总价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
      }
}, {
    id: 'businessInfoPredict',
    title: '商务信息预测',
    type: 'string',
    columnClass: 'text-left',
}, {
    id: 'applyDesc',
    title: '申请说明',
    type: 'string',
    columnClass: 'text-left',
}, {
    id: 'operation',
    title: '操作',
    width: 60,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content += '<a class="btn btn-xs btn-primary" onclick="findDetail(\'' + record.id + '\');"><i class="icon-eye-open"></i>  查看</a>';
        return content;
    }
}, {
    id: 'originReason',
    title: '审批结果',
    type: 'finish',
    width: 80,
    codeTable: status,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        if (value == 'denied') {
            content += '<span style="background:#d9534f;padding:2px 10px;color:white;">未通过</span>';
        }
        if (value == 'promise') {
            content += '<span style="background:#5cb85c;padding:2px 10px;color:white;">已通过</span>';
        }
        return content;
    }
}, {
    id: 'operation',
    title: '报价文件',
    width: 85,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content += '<button class="btn btn-xs btn-info" onclick="down(\'' + record.uploadFilePath + '\');"><i class="icon-cloud-download"></i>  下载</button>';
        return content;
    }
}];

function hidefile() {
    $(".hidefile").hide();
}

function hidefileComplete() {
    if (certusValidateNotnullPolyfill()) {
        $(".hidefile").hide();
    }
}

var quoteItemPronum1 = [{
    id: 'category',
    title: '分类',
    width: 100,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        return getQuoteItem(value);
    }
}, {
    id: 'cataPrice',
    title: '目录价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
      }
}, {
    id: 'discountedRate',
    title: '折扣率',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = value + '%';
        return content;
    }
}, {
    id: 'discountPrice',
    title: '折后价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
      }
}, {
    id: 'taxRate',
    title: '税率',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = value + '%';
        return content;
    }
}, {
    id: 'taxPrice',
    title: '含税价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
      }
}, {
    id: 'descriptor',
    title: '说明',
    type: 'string',
    columnClass: 'text-left',
}];

var quoteItemPronum = [{
    id: 'category',
    title: '分类',
    width: 100,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        return getQuoteItem(value);
    }
}, {
    id: 'cataPrice',
    title: '目录价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
      }
}, {
    id: 'discountedRate',
    title: '折扣率',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = value + '%';
        return content;
    }
}, {
    id: 'discountPrice',
    title: '折后价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
      }
}, {
    id: 'taxRate',
    title: '税率',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = value + '%';
        return content;
    }
}, {
    id: 'taxPrice',
    title: '含税价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
      }
}, {
    id: 'descriptor',
    title: '说明',
    type: 'string',
    columnClass: 'text-left',
}, {
    id: 'operation',
    title: '操作',
    width: 130,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content += '<button class="btn btn-xs btn-info" onclick="modifiedQuoteItem(\'' + record.randomId + '\');"><i class="fa fa-edit"></i>  编辑</button>';
        content += '  ';
        content += '<button class="btn btn-xs btn-danger" onclick="delQuoteItem(\'' + record.randomId + '\');"><i class="fa fa-trash-o"></i>  删除</button>';
        return content;
    }
}];


function isDiffQuote(element) {
    return to2fixed(element.randomId) != to2fixed(randomId);
}

function delQuoteItem(id) {

    layer.confirm('确认删除此数据？', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        randomId = id;
        for (var i in dataInitQuote.exhibitDatas) {
            if (to2fixed(dataInitQuote.exhibitDatas[i].randomId) == to2fixed(id)) {
                $$scope.item = dataInitQuote.exhibitDatas[i];
                // totalmoney -= to2fixed(($$scope.item.cataPrice*$$scope.item.discountedRate/100)*(1+$$scope.item.taxRate/100));
                // $$scope.retainPrice = to2fixed(($$scope.item.cataPrice*$$scope.item.discountedRate/100)*(1+$$scope.item.taxRate/100));
                // $$scope.business.totalBusinessQuatation = totalmoney;
                $$scope.$apply();
            }
        }
        // totalmoney -= to2fixed($$scope.item.cataPrice) * to2fixed($$scope.item.taxRate) / 100;
        dataInitQuote.exhibitDatas = dataInitQuote.exhibitDatas.filter(isDiffQuote);
        caculateTotal(dataInitQuote.exhibitDatas);

        $$scope.item = {};
        dataInitQuote.refresh(false);
        layer.msg('删除成功');
    });



}

function modifiedQuoteItem(id) {

    for (var i in dataInitQuote.exhibitDatas) {
        if (to2fixed(dataInitQuote.exhibitDatas[i].randomId) == to2fixed(id)) {
            $(".hideprice").show();
            $$scope.item = dataInitQuote.exhibitDatas[i];

            randomId = $$scope.item.randomId;
            // $$scope.caculateTotal(dataInitQuote.exhibitDatas.filter(isDiffQuote));
            $$scope.$apply();
        }
    }
}

//文件上传统一字段
function showfile() {
    $(".hidefile").show();
}

function findDetail(id) {
    //打开 俩个 section
    $(".quoteItemOld").show();
    $(".totalQuoteOld").show();

    $CertusFormAjax.ajax("detailOldById", { id: id }, function (res) {

        //更换表格数据
        dataInitQuoteold.exhibitDatas = res.data.datas;
        dataInitQuoteold.refresh(false);
        //更换总价数据
        $$scope.businessold = res.data.business
    })
}

function getQuoteItem(id) {
    if (id == "1") {
        return "软件";
    } else if (id == "2") {
        return "软件license";
    } else if (id == "3") {
        return "硬件";
    } else if (id == "4") {
        return "服务";
    } else if (id == "5") {
        return "软件定制";
    } else if (id == "6") {
        return "一次性折扣";
    }
}

function caculateTotal(datas){

    if($$scope.socket.connected){
        $$scope.socket.emit("caculateTotal",datas);
    }
}